//
//  YDPositionViewController.m
//  PeiZiWangBei
//
//  Created by LK-IOS on 2017/11/8.
//  Copyright © 2017年 LK-IOS. All rights reserved.
//

#import "YDPositionViewController.h"

#import "YDInPositonViewController.h"
#import "YDSettlementViewController.h"
#import "YDOptionalViewController.h"
#import "YDStockSearchViewController.h"

@interface YDPositionViewController ()<UIScrollViewDelegate>

//引导登录页
@property (nonatomic, weak) SYGuideLoginView *guideLoginView;
//标题数组
@property (nonatomic , strong) NSMutableArray *titlesArray;
//滚动的scrollerView
@property (nonatomic , weak) UIScrollView *scrollerView;

//顶部安全区域
@property (nonatomic , assign) CGFloat safeTopH;
//底部安全区域
@property (nonatomic , assign) CGFloat safeBottomH;
/**
 分段控制
 */
@property (nonatomic, strong)UISegmentedControl *segmentControl;

@end

@implementation YDPositionViewController

-(NSMutableArray *)titlesArray
{
    if (_titlesArray == nil) {
        _titlesArray = [NSMutableArray arrayWithObjects:@"自选",@"持仓",@"结算",nil];
    }
    return _titlesArray;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = YES;
    self.view.backgroundColor = [UIColor colorWithHexString:mainGray];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(buySuccess:) name:kBuySuccessNoti object:nil];
    
    [self setNav];
    
}

- (void)setNav
{
    
    [self.navigationController.navigationBar.topItem setTitleView:self.segmentControl];
    UIBarButtonItem *rightItemBtn = [UIBarButtonItem imageWithNormalImage:[UIImage imageNamed:@"buy-search"] hightImage:[UIImage imageNamed:@"buy-search"] addTarget:self action:@selector(rightItemButtonClick:)];
    self.navigationItem.rightBarButtonItem = rightItemBtn;
    self.safeTopH = isPhoneX ? 84 : 64;
    self.safeBottomH = self.isHiddenTabbar ? 0 : (isPhoneX ? 83 : 49);
}


- (void)rightItemButtonClick:(UIButton *)sender
{
    YDStockSearchViewController *vc = [[YDStockSearchViewController alloc] init];
    vc.searchString = @"";
    vc.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:NO];
}
//点买成功通知
- (void)buySuccess:(NSNotification *)noti
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (![SYUserInformation sharedInstance].isLogin || self.scrollerView == nil)return;
        self.deafaultIndex = 1;
        [self selectSegmentWithIndex:self.deafaultIndex];
        
    });
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    if (![SYUserInformation sharedInstance].isLogin) {//没有登录
        if (_scrollerView != nil) {//添加有子视图
            for (UIViewController *vc in self.childViewControllers) {
                [vc.view removeFromSuperview];
                [vc removeFromParentViewController];
            }
            [self.scrollerView removeFromSuperview];
            self.scrollerView = nil;
            [self guideLoginView];
        }else{
            [self guideLoginView];
        }
        
    }else{//无子视图
        if (_guideLoginView != nil) {
            [self.guideLoginView removeFromSuperview];
            self.guideLoginView = nil;
            [self addChildViews];
        }else{
            if (_scrollerView != nil)return;
            [self addChildViews];
        }
    }
    
}

-(void)addChildViews
{
    [self scrollerView];
    [self addChildViewControllers];
    
    [self addChildViewToScrollerView:self.deafaultIndex];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [self selectSegmentWithIndex:self.deafaultIndex];
    });
    
}
- (void)segmentDidSelected:(UISegmentedControl *)segment
{
    if (!self.childViewControllers.count) {return;}
    NSInteger currentIndex =  segment.selectedSegmentIndex;
    [self.scrollerView setContentOffset:CGPointMake(LKScreenW *currentIndex, 0) animated:YES];
    [self addChildViewFromIndex:currentIndex];
}

-(void)selectSegmentWithIndex:(NSInteger)index
{
    self.segmentControl.selectedSegmentIndex = index;
    
    [self.scrollerView setContentOffset:CGPointMake(LKScreenW *index, 0) animated:NO];
    
    [self addChildViewFromIndex:index];
    
}

/**
 添加自控制的view到scrollview
 */
- (void)addChildViewFromIndex:(NSInteger)index
{
    UIViewController *targetvc = [self.childViewControllers objectAtIndex:index];
    
    // 如果已经加载过，就不再加载
    //    if (targetvc.view.superview) return;
    
    targetvc.view.frame = CGRectMake(LKScreenW*index, 0, LKScreenW,self.scrollerView.height);
    [self.scrollerView addSubview:targetvc.view];
}


-(UIScrollView *)scrollerView
{
    if (_scrollerView == nil) {
        UIScrollView *scrollerView = [[UIScrollView alloc] init];
        [self.view addSubview:scrollerView];
        scrollerView.frame = CGRectMake(0, 0, self.view.width , LKScreenH - self.safeTopH - self.safeBottomH);
        scrollerView.backgroundColor = [UIColor colorWithHexString:mainGray];
        scrollerView.scrollsToTop = NO;
        scrollerView.scrollEnabled = NO;
        scrollerView.bounces = NO;
        scrollerView.delegate = self;
        scrollerView.showsHorizontalScrollIndicator = NO;
        scrollerView.showsVerticalScrollIndicator = NO;
        scrollerView.contentSize = CGSizeMake(self.titlesArray.count * scrollerView.width, 0);
        scrollerView.pagingEnabled = YES;
        if (isIos11) {
            self.automaticallyAdjustsScrollViewInsets = NO;
        }
        _scrollerView = scrollerView;
    }
    return _scrollerView;
}


/**
 添加自控制器
 */
-(void)addChildViewControllers
{
    YDOptionalViewController *threevc = [[YDOptionalViewController alloc] init];
    threevc.isHiddenTabbar = self.isHiddenTabbar;
    [self addChildViewController:threevc];
    
    YDInPositonViewController *onevc = [[YDInPositonViewController alloc] init];
    onevc.isHiddenTabbar = self.isHiddenTabbar;
    [self addChildViewController:onevc];
    
    YDSettlementViewController *twovc = [[YDSettlementViewController alloc] init];
    twovc.isHiddenTabbar = self.isHiddenTabbar;
    [self addChildViewController:twovc];
    
    
}

//-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
//{
//
//    CGFloat offsetx = scrollView.contentOffset.x / LKScreenW;
//    if (offsetx <= 0.5) {
//        [self.segmentControl setSelectedSegmentIndex:0];
//    }else if(offsetx <= 1)
//    {
//        [self.segmentControl setSelectedSegmentIndex:1];
//    }else
//    {
//        [self.segmentControl setSelectedSegmentIndex:2];
//    }
//
////    [self addChildViewFromIndex:@(offsetx).integerValue];
//}

/**
 添加对应的子控制器
 */
-(void)addChildViewToScrollerView:(NSInteger)index
{
    UIViewController *childView = self.childViewControllers[index];
    if (childView.view.superview) return;
    //    childView.view.frame = CGRectMake(index * self.scrollerView.width, 0, self.scrollerView.width, self.scrollerView.height);
    [self.scrollerView addSubview:childView.view];
}


-(SYGuideLoginView *)guideLoginView
{
    if (_guideLoginView == nil) {
        //没有登录贴引导登录展位图
        SYGuideLoginView *guideLoginView = [[SYGuideLoginView alloc] init];
        [self.view addSubview:guideLoginView];
        [guideLoginView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.equalTo(self.view);
            make.top.equalTo(isPhoneX ? @(rateX812(40)) : @(rate750(40)));
        }];
        LK(weself)
        [guideLoginView setClickBlock:^(BOOL isClick) {
            YDLoginController *loginVC = [[YDLoginController alloc] init];
            loginVC.loginStyle = Login_Present;
            YDBaseNavigationController *baseNav = [[YDBaseNavigationController alloc] initWithRootViewController:loginVC];
            [weself presentViewController:baseNav animated:YES completion:nil];
        }];
        _guideLoginView = guideLoginView;
    }
    return _guideLoginView;
}

-(UISegmentedControl *)segmentControl
{
    if (_segmentControl == nil) {
        
        UISegmentedControl *segmentControl = [[UISegmentedControl alloc] initWithItems:self.titlesArray];
        segmentControl.frame =CGRectMake(0,0,rate375(260), 26);
        [segmentControl setSelectedSegmentIndex:0];
        segmentControl.tintColor = NumberColor(40, 67, 145);
        [segmentControl addTarget:self action:@selector(segmentDidSelected:) forControlEvents:UIControlEventValueChanged];
        [segmentControl setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor colorWithWhite:1 alpha:0.6],
                                                 NSFontAttributeName:[UIFont systemFontOfSize:16]
                                                 }
                                      forState:UIControlStateNormal];
        
        [segmentControl setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor],
                                                 NSFontAttributeName:[UIFont systemFontOfSize:16]}
                                      forState:UIControlStateSelected];
        
        _segmentControl = segmentControl;
    }
    return _segmentControl;
}



@end
